package com.lujianfei.layout_behavior.behavior;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

public class HeaderBehavior extends CoordinatorLayout.Behavior<View> {
    final static String TAG = "HeaderBehavior==";

    // 记录手指触摸的位置
    private int mLastY = 0;
    private boolean mTouchInSide = false;

    public HeaderBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(CoordinatorLayout parent, View child, MotionEvent ev) {
        // 手指触摸的回调
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = (int) ev.getRawY();
                mTouchInSide = touchOnView(ev.getRawX(), ev.getRawY(), child);
                break;
            case MotionEvent.ACTION_MOVE:
                int y = (int) ev.getRawY();
                if (mTouchInSide) {
                    child.setTranslationY(child.getTranslationY() + y - mLastY);
                }
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:
                mTouchInSide = false;
                break;
        }
        return true;
    }

    boolean touchOnView(float x,float y,View view) {
        int[] point = new int[2];
        view.getLocationOnScreen(point);
        Log.d(TAG, String.format("view (%s,%s)(%s,%s) touch (%s,%s)",point[0],point[1],point[0]+view.getWidth(),point[1]+view.getHeight()
                ,x,y));
        // x ~ x + view.getWidth()
        // y ~ y + view.getHeight()
        boolean inX = point[0] <= x && x <= point[0] + view.getWidth();
        boolean inY = point[1] <= y && y <= point[1] + view.getHeight();
        return inX && inY;
    }
}